package com.blog.controller;

import cn.hutool.crypto.digest.MD5;
import com.blog.pojo.Articles;
import com.blog.pojo.User;
import com.blog.service.ArticleService;
import com.blog.service.FolloweeService;
import com.blog.service.UserService;
import com.blog.service.impl.ArticleServiceImpl;
import com.blog.service.impl.FolloweeServiceImpl;
import com.blog.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
@WebServlet("/userServlet")
public class UserServlet extends BaseServlet{
    private UserService userService=new UserServiceImpl();
    private FolloweeService followeeService=new FolloweeServiceImpl();
    private ArticleService articleService=new ArticleServiceImpl();
//
    //添加
    public String addUser(HttpServletRequest req, HttpServletResponse resp)  {
        //获取参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String phone=  req.getParameter("phone");
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        //调用业务层
        userService.addUser(user);
        req.setAttribute("username",username);
        req.setAttribute("password",password);
        req.setAttribute("phone",phone);

        return  "forward:/userList.jsp";
    }

    //删除
    public String deleteUser(HttpServletRequest req, HttpServletResponse resp)  {

        //登录验证
        HttpSession session=req.getSession();
      User user=(User)session.getAttribute("user");
      if(user==null){
          req.setAttribute("msg","请先登录");
          return "forward:/login.jsp";
      }else {

          //获取参数
          String id = req.getParameter("id");
          if (id == null) {
              req.setAttribute("msg", "用户不存在");
              return "forward:/error.jsp";
          }else {
              int idInt = Integer.parseInt(id);
              boolean delete = userService.delete(idInt);
              if (delete) {
                  return "forward:/userServlet?method=findAll";
              } else {
                  req.setAttribute("msg", "删除失败");
                  return "forward:/error.jsp";
              }
          }
      }
    }

    //更新
    public String updateUser(HttpServletRequest req, HttpServletResponse resp)  {
        //获取参数
        String id=req.getParameter("id");
        //登录验证
        HttpSession session=req.getSession();
        User user=(User)session.getAttribute("user");
        if(user==null){
            req.setAttribute("msg","请先登录");
            return "forward:/login.jsp";
        }else{
            int idInt=Integer.parseInt(id);

            User user1=new User();
            user1.setId(idInt);
            user1.setUsername(req.getParameter("username"));
            user1.setPassword(req.getParameter("password"));
            user1.setPhone(req.getParameter("phone"));
            user1.setCreatedAt(LocalDateTime.now());
            //调用业务层
            boolean update = userService.update(user1);
            if(update){
                 User user2= userService.findById(user.getId());
                req.setAttribute("user",user2);
                return "forward:/userUpdate.jsp";
            }else{
                req.setAttribute("msg","更新失败");
                return "forward:/error.jsp";
            }
        }
    }
    //根据id查找用户
  public  String findById(HttpServletRequest req, HttpServletResponse resp)  {
        //1.参数获取
      String id=req.getParameter("id");
      //登录验证
      HttpSession session=req.getSession();
      User user=(User)session.getAttribute("user");
      session.setAttribute("user", user);
      if(user==null){
          req.setAttribute("msg","请先登录");
          return "forward:/login.jsp";
      }else {

              int idInt = Integer.parseInt(id);
              User user1 = userService.findById(idInt);
              req.setAttribute("user", user);
              return "forward:/userUpdate.jsp";

      }
    }

    //查看全部
    public String findAll(HttpServletRequest req, HttpServletResponse resp)  {
        //1.获取参数----查找全部用户无参数
        //2.调用业务层
        List<User> userList = userService.findAll();
        req.setAttribute("userList", userList);
        return "forward:/userList.jsp";
    }

   public String findByLoginUserId( HttpServletRequest req, HttpServletResponse resp){
       //2.登录验证
       HttpSession session = req.getSession();
       User loginUser = (User) session.getAttribute("user");
       if (loginUser == null) {
           req.setAttribute("msg", "请先登录");
           return "forward:/login.jsp";
       }
       Integer userIdInt =loginUser.getId();


       boolean isOwner = loginUser.getId() == userIdInt;
       boolean isFollowed = followeeService.findByUserIdAndFolloweeId(loginUser.getId(), userIdInt) != null;
       req.setAttribute("isFollowed", isFollowed);
       //获取该作者所有文章
       List<Articles> articles = articleService.finbByUserId(userIdInt);
       for (Articles article : articles) {

           if (loginUser != null) {
               boolean like = articleService.userLiked(article.getId(), loginUser.getId());
               boolean favorite = articleService.userFavorited(article.getId(), loginUser.getId());
               article.setUserLiked(like);
               article.setUserFavorited(favorite);

               boolean isAuthor = article.getUserId() == loginUser.getId();
               article.setCanEdit(isAuthor);
               article.setCanDelete(isAuthor);

           }
       }
       // 获取关注数量
       int followeeCount = followeeService.findFolloweeCount(userIdInt);
       //获取粉丝数（service）
       int fanCount = followeeService.findFanCount(userIdInt);
       // 添加经验值获取逻辑
       int experiencePoints = userService.findExperience(userIdInt);

       req.setAttribute("followeeCount", followeeCount);
       req.setAttribute("fanCount", fanCount);
       req.setAttribute("isOwner", isOwner);
       req.setAttribute("experiencePoints", experiencePoints);
       req.setAttribute("articles", articles);

       return "forward:/userProfile.jsp";

   }





//    public static void main(String[] args) {
//
//        MD5 md5 = new MD5();
//        String password = "123456";
//        String encryptPassword = md5.digestHex(password, "utf-8");
//        System.out.println(encryptPassword);
//
//        encryptPassword = md5.digestHex(password, "utf-8");
//        System.out.println(encryptPassword);
//    }
}
